package cn.geminis.fabric.service.controller;

import cn.geminis.fabric.core.model.BlockInfo;
import cn.geminis.fabric.service.service.ChaincodeService;
import lombok.RequiredArgsConstructor;
import org.hyperledger.fabric.gateway.Gateway;
import org.springframework.web.bind.annotation.*;

/**
 * @author puddi
 */
@RestController
@RequestMapping("/block")
@RequiredArgsConstructor
public class BlockController {

    private final static String TXID_PREFIX = "TXID_";

    private final Gateway gateway;
    private final ChaincodeService chaincodeService;

    @GetMapping("/{channel}/{chaincode}/{id}")
    @ResponseBody
    public BlockInfo get(@PathVariable String channel,
                         @PathVariable String chaincode,
                         @PathVariable String id) throws Exception {

        var txid = chaincodeService.get(channel, chaincode, TXID_PREFIX + id);

        var network = gateway.getNetwork(channel);
        var info = network.getChannel().queryBlockByTransactionID(txid);
        var result = new BlockInfo();
        result.setTxid(txid);
        result.setNumber(info.getBlockNumber());
        result.setHash(info.getDataHash());
        return result;
    }


}
